import sys
import os

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from concurrent.futures import ThreadPoolExecutor
import asyncio

from common.database import init_db
from net.config import current_config
from net.routes.net_routes import (
    router as letter_router,
    set_global_variables as set_letter_variables,
)
from net.routes.monitor_routes import (
    router as monitor_router,
    set_global_variables as set_monitor_variables,
)

# 创建线程池
thread_pool = ThreadPoolExecutor(max_workers=15)

# 创建请求队列和信号量
REQUEST_QUEUE = asyncio.Queue(maxsize=100)
REQUEST_SEMAPHORE = asyncio.Semaphore(10)  # 调整并发数到10

# 新增：用于存储实时调用记录的全局字典
CALL_RECORDS = {}


async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    # 只在主进程中初始化数据库，避免热重载时重复初始化
    if not os.environ.get("UVICORN_RELOAD_PROCESS"):
        print("🚀 主进程启动，初始化数据库...")
        init_db(current_config["database_url"])
    else:
        print("🔄 热重载进程启动，跳过数据库初始化...")

    # 设置路由模块的全局变量
    set_letter_variables(CALL_RECORDS, thread_pool)
    set_monitor_variables(CALL_RECORDS, REQUEST_QUEUE, thread_pool)

    yield


app = FastAPI(title="网络信访件信息查询API", lifespan=lifespan)

# 挂载静态文件目录
static_files_dir = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "static"
)
app.mount("/static", StaticFiles(directory=static_files_dir), name="static")


@app.get("/net", include_in_schema=False)
async def get_net_monitor_page():
    """获取网络监控页面"""
    return FileResponse(os.path.join(static_files_dir, "net_index.html"))


# 注册路由
app.include_router(letter_router)
app.include_router(monitor_router)


if __name__ == "__main__":
    import uvicorn

    print(f"正在启动网络信访件信息查询API...")
    print(f"服务地址: http://{current_config['host']}:{current_config['port']}")
    print(f"API文档: http://{current_config['host']}:{current_config['port']}/docs")
    print("按 Ctrl+C 停止服务")

    uvicorn.run(
        "net.app:app",
        host=current_config["host"],
        port=current_config["port"],
        reload=True,  # 启用热重载
    )
